import React, { useState, useEffect, useRef, memo, lazy, Suspense } from 'react';
import { 
  Table, 
  Tag, 
  Space, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  DatePicker, 
  Upload, 
  Progress,
  Popover,
  Typography,
  message,
  Layout
} from 'antd';
import { 
  PlusOutlined, 
  UploadOutlined, 
  EditOutlined, 
  DeleteOutlined,
  FileTextOutlined,
  LinkOutlined
} from '@ant-design/icons';
import moment from 'moment';
import api from '../utils/api';
import axios from 'axios'; // Import axios
import { useAuth } from '../context/AuthContext';
import 'react-quill/dist/quill.snow.css'; // 
import TaskSearchBar from '../components/TaskSearchBar';
import { Layout as AntLayout } from 'antd'; // u6062u590du6587u4ef6u5934u90e8u7684u5bfcu5165u90e8u5206
import Header from '../components/Header'; // u5bfcu5165u5171u7528u7684Headeru7ec4u4ef6
import useTheme from '../hooks/useTheme'; // u5bfcu5165u4e3bu9898u94a9u5b50

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title } = Typography;

// 
const formatDate = (dateString) => {
  if (!dateString) return null;
  // 
  const date = moment(dateString).format('YYYY-MM-DD');
  console.log("date ===== "+date)
  return date;
};

// 
const parseDate = (dateString) => {
  if (!dateString) return null;
  // 
  return null;
};

// 
const TASK_STATUS = {
  IN_PROGRESS: { text: '进行中', color: 'blue' },
  NOT_STARTED: { text: '未开始', color: 'orange' },
  COMPLETED: { text: '已完成', color: 'green' },
  TEST: { text: '测试中', color: 'purple' }
};

// 
const MemoizedTable = memo(({ columns, dataSource, loading, pagination }) => {
  return (
    <Table 
      columns={columns} 
      dataSource={dataSource} 
      rowKey="id"
      loading={loading}
      pagination={pagination}
      virtual={false}
      className="custom-table"
      scroll={{ x: 1000 }} // 
    />
  );
});

// 
const LazyTable = lazy(() => {
  // 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        default: MemoizedTable
      });
    }, 200);
  });
});

// 
const LazyReactQuill = lazy(() => {
  // 
  import('react-quill/dist/quill.snow.css');
  
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        default: (props) => {
          // 
          const editorRef = useRef(null);
          const [editor, setEditor] = useState(null);
          
          useEffect(() => {
            // 
            if (typeof window !== 'undefined') {
              import('react-quill').then(ReactQuill => {
                if (editorRef.current && !editor) {
                  // 
                  const quillEditor = new ReactQuill.default(editorRef.current, {
                    modules: props.modules,
                    placeholder: props.placeholder,
                    theme: props.theme || 'snow',
                    readOnly: props.readOnly
                  });
                  
                  setEditor(quillEditor);
                  
                  // 
                  if (props.value) {
                    quillEditor.clipboard.dangerouslyPasteHTML(props.value);
                  }
                  
                  // 
                  quillEditor.on('text-change', () => {
                    if (props.onChange) {
                      props.onChange(quillEditor.root.innerHTML);
                    }
                  });
                }
              });
            }
            
            return () => {
              // 
              if (editor) {
                try {
                  editor.off('text-change');
                } catch (e) {
                  console.error('', e);
                }
              }
            };
          }, []);
          
          // 
          useEffect(() => {
            if (editor && props.value !== undefined) {
              const currentContent = editor.root.innerHTML;
              if (props.value !== currentContent) {
                editor.clipboard.dangerouslyPasteHTML(props.value || '');
              }
            }
          }, [props.value, editor]);
          
          return (
            <div className="quill-editor-container">
              <div ref={editorRef} style={{ height: '200px', border: '1px solid #ddd', borderRadius: '4px' }} />
            </div>
          );
        }
      });
    }, 100);
  });
});

const TaskManagementPage = () => {
  const { user } = useAuth();
  const [tasks, setTasks] = useState([]);
  const [initialTasks, setInitialTasks] = useState([]);
  const [projects, setProjects] = useState([]); // 
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isViewMode, setIsViewMode] = useState(false);
  const [currentTask, setCurrentTask] = useState(null); // 
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState(0); // 
  const [editingRecord, setEditingRecord] = useState(null); // 
  const [newTask, setNewTask] = useState({ id: '', name: '', completed: false });
  const inputRef = useRef(null);
  const [tableReady, setTableReady] = useState(false);
  const [total, setTotal] = useState(0); // 
  const [darkMode, setDarkMode] = useTheme(); // 

  // 
  const modules = {
    toolbar: [
      [{ 'header': [1, 2, 3, false] }],
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      ['link', 'image'],
      ['clean']
    ],
  };

  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const response = await api.get('/api/project/list');
        console.log("response  == "+response.data.data)
        if (response.data) {
         
          setProjects(response.data.data || []);
        }
      } catch (error) {
        console.error('', error);
      }
    };
    fetchProjects();
  }, []);

  // 
  const fetchTasks = async () => {
    setLoading(true);
    try {
      const response = await api.get('/api/task/list');
      if (response.data && response.data.code === '200') {
        setTasks(response.data.data || []);
        setInitialTasks(response.data.data || []);
      } else {
        message.error('' + (response.data.message || ''));
      }
    } catch (error) {
      console.error('', error);
      message.error('' + (error.message || ''));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTasks();
    
    // 
    const timer = setTimeout(() => {
      setTableReady(true);
    }, 100);
    
    return () => clearTimeout(timer);
  }, []);

  // 
  const edit = (record) => {
    console.log("", record);
    
    // 
    if (editingKey !== 0) {
      // 
      cancel();
    }
    
    // 
    const taskId = record.taskId || record.id || record.key;
    console.log("=", taskId);
    console.log("record.startTime = "+record.startTime)
    setEditingKey(taskId);
 
    setEditingRecord({
      ...record,
      taskId: taskId, // 
      startTime: formatDate(record.startTime),
      endTime: formatDate(record.endTime),
      // 
      projectName: record.projectName
    });
    
    // 
    setTimeout(() => {
      console.log("=", editingKey);
      console.log("=", editingRecord);
    }, 0);
  };

  // 
  const cancel = () => {
    console.log("", editingKey, "", 0);
    
    // 
    if (editingRecord && editingRecord.id < 0) {
      console.log("", editingRecord);
      setTasks(prevTasks => prevTasks.filter(task => task.id !== editingRecord.id));
    }
    
    setEditingKey(0);
    setEditingRecord(null);
  };

  // 
  const save = async (key) => {
    try {
      console.log("", key);
      if (!editingRecord) {
        message.error('');
        return;
      }
      
      const taskId = editingRecord.taskId || key;
      console.log("=", taskId);
      console.log("=", editingRecord.startTime);
      // 
      const formattedRecord = {
        ...editingRecord,
        startTime: formatDate(editingRecord.startTime),
        endTime: formatDate(editingRecord.endTime)
      };
      
      // 
      const selectedProject = projects.find(p => p.id.toString() === formattedRecord.projectId.toString());
      if (selectedProject) {
        formattedRecord.projectName = selectedProject.projectName;
        formattedRecord.projectId = selectedProject.id;
        console.log('', selectedProject);
      } else {
        message.error('');
        return;
      }
      
      const formData = {
        ...formattedRecord,
      };
      
      // 
      if (editingRecord && editingRecord.id && editingRecord.id > 0) {
        formData.taskId = taskId;
      }
      
      console.log("=", formData);
      
      let response;
      if (editingRecord && editingRecord.taskId && editingRecord.taskId > 0) {
        // 
        response = await api.put(`/api/task/update`, {
          ...formData,
          taskId: editingRecord.taskId
        });
      } else {
        // 
        response = await api.post('/api/task/create', formData);
      }
      
      if (response.data && response.data.code === '200') {
        message.success('');
        const newData = [...tasks];
        const index = newData.findIndex(item => taskId === (item.taskId || item.id || item.key));
        if (index > -1) {
          const item = newData[index];
          // 
          const updatedRecord = { 
            ...item, 
            ...editingRecord,
            // 
            projectName: selectedProject.projectName
          };
          newData.splice(index, 1, updatedRecord);
          setTasks(newData);
          setEditingKey(0);
          setEditingRecord(null);
        } else {
          console.error("", taskId);
          message.warning('');
          // 
          fetchTasks();
        }
      } else {
        message.error('' + (response.data.message || ''));
      }
    } catch (error) {
      console.error('', error);
      message.error('' + (error.message || ''));
    }
  };

  // 
  const columns = [
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
      width: 200,
      align: 'center', // 
      render: (text, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        return isEditing ? (
          <Input
            value={editingRecord?.taskName}
            onChange={(e) => setEditingRecord({ ...editingRecord, taskName: e.target.value })}
          />
        ) : (
          <span>{text}</span>
        );
      },
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 120,
      align: 'center', // 
      render: (text, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        return isEditing ? (
          <Select
            value={editingRecord?.projectId}
            onChange={(value) => {
              // 
              const selectedProject = projects.find(p => p.id.toString() === value.toString());
              // 
              setEditingRecord({ 
                ...editingRecord, 
                projectId: value === 'null' ? null : value,
                projectName: selectedProject ? selectedProject.projectName : ''
              });
            }}
            style={{ width: '120px' }}
          >
            {projects.map((project, index) => (
              <Select.Option key={project.id || `project-${index}`} value={project.id}>
                {project.projectName || ''}
              </Select.Option>
            ))}
          </Select>
        ) : (
          <span>{text}</span>
        );
      },
    },
    {
      title: '任务详情',
      dataIndex: 'taskDetail',
      key: 'taskDetail',
      width: 100,
      align: 'center', // 
      render: (text, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        return isEditing ? (
          <Input.TextArea
            value={editingRecord?.taskDetail}
            onChange={(e) => setEditingRecord({ ...editingRecord, taskDetail: e.target.value })}
          />
        ) : (
          <span>
            {text ? (
              <Popover 
                content={<div dangerouslySetInnerHTML={{ __html: text }} />} 
                title="Task Detail" 
                trigger="click"
              >
               <div style={{ margin: '0 0 0 -30px' }}>
               <Button type="link" icon={<FileTextOutlined />}>查看详情</Button>
               </div>
              </Popover>
            ) : (
              <span>-</span>
            )}
          </span>
        );
      },
    },
    {
      title: '分支',
      dataIndex: 'branch',
      key: 'branch',
      width: 100,
      align: 'center',
      render: (text, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        return isEditing ? (
          <Input
            value={editingRecord?.branch}
            onChange={(e) => setEditingRecord({ ...editingRecord, branch: e.target.value })}
          />
        ) : (
          <span>{text}</span>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'currentStatus',
      key: 'currentStatus',
      width: 50,
      align: 'center', // 
      render: (status, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        return isEditing ? (
          <Select
            value={editingRecord?.currentStatus}
            onChange={(value) => setEditingRecord({ ...editingRecord, currentStatus: value })}
          >
            {Object.entries(TASK_STATUS).map(([key, value]) => (
              <Option key={key} value={key}>{value.text}</Option>
            ))}
          </Select>
        ) : (
          <span>
            <Tag color={TASK_STATUS[status]?.color || 'default'}>
              {TASK_STATUS[status]?.text || status || ''}
            </Tag>
          </span>
        );
      },
      filters: [
        { text: '未开始', value: 'NOT_STARTED' },
        { text: '进行中', value: 'IN_PROGRESS' },
        { text: '已完成', value: 'COMPLETED' },
        { text: '测试中', value: 'TEST' },
      ],
      onFilter: (value, record) => record.currentStatus === value,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 80,
      align: 'center', // 
      render: (text, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        return isEditing ? (
          <DatePicker
            format="YYYY-MM-DD"
            // 
            // value={parseDate(editingRecord?.startTime)}
            onChange={(date) => {
              console.log("", date);
              const formattedDate = date ? date.format('YYYY-MM-DD') : null;
              console.log("", formattedDate);
              setEditingRecord({
                ...editingRecord,
                startTime: formattedDate
              });
            }}
            style={{ width: '100%' }}
            inputReadOnly={true}
            // 
            placeholder={editingRecord?.startTime || ""}
          />
        ) : (
          <span>{text ? formatDate(text) : '-'}</span>
        );
      },
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 80,
      align: 'center', // 
      render: (text, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        return isEditing ? (
          <DatePicker
            format="YYYY-MM-DD"
            // 
            // value={parseDate(editingRecord?.endTime)}
            onChange={(date) => {
              console.log("", date);
              const formattedDate = date ? date.format('YYYY-MM-DD') : null;
              console.log("", formattedDate);
              setEditingRecord({
                ...editingRecord,
                endTime: formattedDate
              });
            }}
            style={{ width: '100%' }}
            inputReadOnly={true}
            // 
            placeholder={editingRecord?.endTime || ""}
          />
        ) : (
          <span>{text ? formatDate(text) : '-'}</span>
        );
      },
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 120,
      align: 'center', // 
      render: (_, record) => {
        const recordId = record.taskId || record.id || record.key;
        const isEditing = recordId === editingKey;
        
        return (
          <span>
            {isEditing ? (
              <Space>
                <Button type="primary" onClick={() => save(recordId)} size="small">
                  保存
                </Button>
                <Button onClick={() => cancel()} size="small">
                  取消
                </Button>
              </Space>
            ) : (
              <Space>
                <Button 
                  type="primary" 
                  disabled={editingKey !== 0}
                  onClick={() => edit(record)}
                  size="small"
                >
                  编辑
                </Button>
                <Button 
                  type="primary" 
                  onClick={() => handleAddSubTask(record)}
                  size="small"
                >
                  添加子任务
                </Button>
                <Button 
                  type="primary" 
                  danger
                  disabled={editingKey !== 0}
                  onClick={() => handleDelete(record)}
                  size="small"
                >
                  删除
                </Button>
              </Space>
            )}
          </span>
        );
      },
    },
  ];

  // 
  const showModal = (task = null, viewOnly = false) => {
    setCurrentTask(task);
    setIsViewMode(viewOnly);
    
    if (task) {
      form.setFieldsValue({
        taskName: task.taskName,
        projectId: task.projectId ? task.projectId.toString() : null,
        taskDetail: task.taskDetail,
        startTime: formatDate(task.startTime),
        endTime: formatDate(task.endTime),
        currentStatus: task.currentStatus,
        progress: task.progress,
      });
    } else {
      form.resetFields();
    }
    
    setIsModalVisible(true);
  };

  // 
  const handleDelete = (task) => {
    Modal.confirm({
      title: '',
      content: `""${task.taskName}"?`,
      okText: '',
      cancelText: '',
      onOk: async () => {
        try {
          const response = await api.delete(`/api/task/delete/${task.id}`);
          if (response.data && response.data.code === '200') {
            message.success('');
            fetchTasks();
          } else {
            message.error('' + (response.data.message || ''));
          }
        } catch (error) {
          console.error('', error);
          message.error('' + (error.message || ''));
        }
      }
    });
  };

  // 
  const handleCancel = () => {
    setIsModalVisible(false);
    // 
    setTimeout(() => {
      form.resetFields();
    }, 100);
  };

  const handleAddSubTask = (parentTask) => {
    // 生成一个临时的负ID，确保不会与现有任务ID冲突
    const tempId = -Math.floor(Math.random() * 1000000);
    
    // 创建子任务的初始数据
    const subTask = {
      id: tempId,
      taskId: tempId,
      taskName: '', // 空白任务名称
      projectId: parentTask.projectId,
      projectName: parentTask.projectName,
      currentStatus: 'NOT_STARTED',
      progress: 0,
      parent_id: parentTask.id || parentTask.taskId // 设置父任务ID
    };

    // 找到父任务在数组中的索引
    const parentIndex = tasks.findIndex(task => 
      (task.id === parentTask.id) || (task.taskId === parentTask.taskId)
    );
    
    if (parentIndex !== -1) {
      // 创建新的任务数组，在父任务后插入子任务
      const newTasks = [...tasks];
      newTasks.splice(parentIndex + 1, 0, subTask);
      setTasks(newTasks);
      
      // 立即进入编辑模式
      setEditingKey(tempId);
      setEditingRecord(subTask);
    } else {
      message.error('无法找到父任务');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (!values.projectId) {
        message.error('请选择项目');
        return;
      }
      
      // 获取选中的项目信息
      const selectedProject = projects.find(p => p.id.toString() === values.projectId.toString());
      if (selectedProject) {
        values.projectName = selectedProject.projectName;
        values.projectId = selectedProject.id;
        console.log('选中的项目:', selectedProject);
        console.log('表单数据:', values);
      } else {
        message.error('无法找到选中的项目');
        return;
      }
      
      // 准备表单数据
      const formData = {
        ...values,
        // 处理日期格式
        startTime: values.startTime ? formatDate(values.startTime) : (currentTask?.startTime || null),
        endTime: values.endTime ? formatDate(values.endTime) : (currentTask?.endTime || null),
        // 如果是子任务，添加parent_id
        parent_id: currentTask?.parent_id || null
      };
      
      setLoading(true);
      
      let response;
      if (editingRecord && editingRecord.id && editingRecord.id > 0) {
        // 更新任务
        response = await api.put(`/api/task/update`, {
          ...formData,
          taskId: editingRecord.id
        });
      } else {
        // 创建新任务
        response = await api.post('/api/task/create', formData);
      }
      
      if (response.data && response.data.code === '200') {
        message.success(currentTask ? '更新任务成功' : '创建任务成功');
        setIsModalVisible(false);
        fetchTasks();
      } else {
        message.error((currentTask ? '更新任务失败: ' : '创建任务失败: ') + '' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('提交表单失败:', error);
      message.error('操作失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const handleAddTask = () => {
    setNewTask({ id: Date.now(), name: '', completed: false });
  };

  const handleCompleteTask = () => {
    // 
    if (editingKey !== 0) {
      message.warning('');
      return;
    }
    
    // 
    const uniqueId = -Math.floor(Math.random() * 10000) - 1;
    
    // 
    const newTask = { 
      id: uniqueId, 
      taskId: uniqueId, // 
      title: '', 
      taskName: '', // 
      isEditing: true, 
      currentStatus: 'IN_PROGRESS', 
      progress: 0 
    };
    
    setTasks(prevState => ([newTask, ...prevState]));
    setNewTask({ id: '', name: '', completed: false });
    edit(newTask);
  };

  const handleSearch = async ({ taskName, projectId, status, taskDetail }) => {
    setLoading(true);
    try {
      // 
      const params = new URLSearchParams();
      if (taskName) params.append('taskName', taskName);
      if (projectId) params.append('projectId', projectId);
      // 
      if (status && status !== 'ALL') params.append('currentStatus', status);
      if (taskDetail) params.append('taskDetail', taskDetail);
      
      // 
      params.append('page', 1);
      params.append('size', 10);
      
      // 
      const response = await api.get(`/api/task/page?${params.toString()}`);
      
      if (response.data && response.data.code === '200') {
        setTasks(response.data.data.records || []);
        setTotal(response.data.data.total || 0); // 
        // 
        if (!taskName && !projectId && !status && !taskDetail) {
          setInitialTasks(response.data.data.records || []);
        }
      } else {
        message.error('' + (response.data.message || ''));
      }
    } catch (error) {
      console.error('', error);
      message.error('' + (error.message || ''));
    } finally {
      setLoading(false);
    }
  };

  return (
    <AntLayout className={darkMode ? 'dark' : ''} style={{ background: 'var(--bg-color)' }}>
      <Header 
        darkMode={darkMode} 
        setDarkMode={setDarkMode}
        onNewProject={() => message.info('')}
      />
      <AntLayout.Content style={{ paddingTop: 84, margin: 0, padding: '2rem 1rem', maxWidth: '100%' }}>
        <div className="task-management-page" style={{ width: '100%' }}>
          <TaskSearchBar onSearch={handleSearch} handleCompleteTask={handleCompleteTask} />
          
          {tableReady ? (
            <Suspense fallback={<div></div>}>
              <LazyTable 
                columns={columns} 
                dataSource={tasks} 
                loading={loading}
                pagination={{ 
                  current: 1,  // 
                  pageSize: 10, // 
                  showSizeChanger: true, 
                  showTotal: (total) => `共 ${total} 条记录`,
                  total: total, // 
                  onChange: (page, pageSize) => {
                    // 
                    const params = new URLSearchParams();
                    params.append('page', page);
                    params.append('size', pageSize);
                    // 
                    const searchForm = document.querySelector('form');
                    if (searchForm) {
                      const taskNameInput = searchForm.querySelector('input[placeholder="搜索任务"]');
                      const projectNameInput = searchForm.querySelector('input[placeholder="搜索项目"]');
                      // 
                      const statusSelect = searchForm.querySelector('.ant-select-selection-item');
                      const taskDetailInput = searchForm.querySelector('input[placeholder="搜索详情"]');
                      
                      if (taskNameInput && taskNameInput.value) params.append('taskName', taskNameInput.value);
                      if (projectNameInput && projectNameInput.value) params.append('projectId', projectNameInput.value);
                      // 
                      if (statusSelect) {
                        const statusValue = statusSelect.getAttribute('title');
                        // 如果状态下拉框有值，则取其title属性值
                        if (statusValue && statusValue !== '全部') {
                          Object.entries(TASK_STATUS).forEach(([key, value]) => {
                            if (value.text === statusValue) {
                              params.append('currentStatus', key);
                            }
                          });
                        } else if (statusValue === '全部') {
                          // 如果选择了"全部"选项，则不传入currentStatus参数
                          // params.append('currentStatus', '');
                        }
                      }
                      if (taskDetailInput && taskDetailInput.value) params.append('taskDetail', taskDetailInput.value);
                    }
                    
                    // 
                    setLoading(true);
                    api.get(`/api/task/page?${params.toString()}`)
                      .then(response => {
                        if (response.data && response.data.code === '200') {
                          setTasks(response.data.data.records || []);
                          setTotal(response.data.data.total || 0); // 
                        } else {
                          message.error('获取任务列表失败: ' + (response.data.message || '未知错误'));
                        }
                      })
                      .catch(error => {
                        console.error('获取任务列表失败:', error);
                        message.error('获取任务列表失败: ' + (error.message || '未知错误'));
                      })
                      .finally(() => {
                        setLoading(false);
                      });
                  }
                }}
                size="middle"
                className="custom-table" // 
              />
            </Suspense>
          ) : (
            <div></div>
          )}
          
          <Modal 
            title={currentTask ? '' : ''}
            visible={isModalVisible}
            onOk={handleSubmit}
            onCancel={handleCancel}
            destroyOnClose={true}
            width={800}
          >
            <Form 
              form={form} 
              layout="vertical"
              initialValues={{
                currentStatus: 'NOT_STARTED',
                progress: 0,
              }}
            >
              <Form.Item label="" name="taskName">
                <Input />
              </Form.Item>
              <Form.Item label="" name="projectId">
                <Select>
                  {projects.map((project, index) => (
                    <Select.Option key={project.id || `project-${index}`} value={project.id}>
                      {project.projectName || ''}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item label="" name="taskDetail">
                <Input.TextArea rows={4} />
              </Form.Item>
              <Form.Item label="" name="startTime">
                <DatePicker 
                  format="YYYY-MM-DD"
                  style={{ width: '100%' }}
                  placeholder={currentTask?.startTime || ""}
                  inputReadOnly={true}
                />
              </Form.Item>
              <Form.Item label="" name="endTime">
                <DatePicker 
                  format="YYYY-MM-DD"
                  style={{ width: '100%'}}
                  placeholder={currentTask?.endTime || ""}
                  inputReadOnly={true}
                />
              </Form.Item>
              <Form.Item label="aa" name="currentStatus">
                <Select>
                  {Object.entries(TASK_STATUS).map(([key, value]) => (
                    <Select.Option key={key} value={key}>{value.text}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Form>
          </Modal>
        
        </div>
      </AntLayout.Content>
    </AntLayout>
  );
};

export default TaskManagementPage;
